var EventProxy = require('eventproxy');
var logger = require('../service/Logger');
var Activity = require('../proxy').Activity;
var Faction = require('../proxy').Faction;
var FactionMember = require('../proxy').FactionMember;
var redisManager = require('../proxy').RedisManager;
var User = require('../proxy').User;
var Message = require('../proxy').Message;
var dateUtil = require('../utils/DateUtil');
var WeiXinApi =require('../lib/WeiXinApi');
var config = require('../config').config;

exports.create = function (req, res, next){
    var factionId = req.params.faction;
    res.render('activity/create', {factionId: factionId});
}

exports.createFactionAct = function(req, res, next){
    var factionId = req.params.faction;
    /*Faction.findById(factionId, function(err, faction){
        if(err){logger.error(err.message); return res.render('others/error',{error:err})}
        res.render('activity/create_faction_act', {factionId: factionId, faction: faction});
    })*/
    res.render('activity/create_faction_act', {factionId: factionId});
}

exports.save = function(req, res, next){
    var name = req.body.actname,
        startTime = req.body.startTime,
        location = req.body.actlocation,
        remark = req.body.remark,
        hasContact = req.body.hasContact,
        hasBusiness = req.body.hasBusiness,
        factionId = req.body.factionId,
        score = req.body.actscore,
        type = req.body.acttype,
        creator = req.params.currentUser;
    var actId = req.body.actid;
    if(actId){
        Activity.updateAct(actId, name, startTime, location, remark,
            creator, hasContact, hasBusiness, factionId, score, type, function(err, resp){
                res.send({data: {_id: actId}});
            })
    }else{
        Activity.newAndSave(name, startTime, location, remark,
            creator, hasContact, hasBusiness, factionId, score, type, function(err, act){
                if(err){logger.error(err.message);return res.send({error: err});}
                Activity.addAtend(act._id, creator, function(err, data){
                    console.log('creator join attends...')
                });
                //区分圈内活动不发joinCode
                if(act.belongFaction){
                    res.send({data: act, joinCode: ''})
                }else{
                    //生成4位邀请码
                    var joinCode = act.joinCode;
                    cacheJoinCode(act.id, joinCode, 10, function(){
                        return res.send({data: act, joinCode: joinCode, needalert: needAlert(act)});
                    });
                }
            })
    }
}
function cacheJoinCode(actId, joinCode, delayMin, callback){
    var obj = {
        actId: actId,
        vaildTime: new Date().getTime() + delayMin*60000
    }
    limitStackMap.set(joinCode, obj);
    callback();
}


function needAlert(act){
    if(act.startTime.getTime() > new Date().getTime()){
        return false;
    }else{
        return true;
    }
}

exports.getJoinCode = function(req, res){
    var me = req.params.currentUser;
    var code = req.params.code;
    redisManager.getAccesstoken(function(err, token){
        var content = ' 成功发起了聚会！\n'+
            '\n 伙伴们已经入座？\n'+
            '\n 告知大家在快乐邦公众号输入暗号：'+code+'\n'+
            '\n (10分钟内有效哦)';
        WeiXinApi.sendCustomerTextMsg(token, me.openid, content, function(err, data){
            logger.debug('sent joinCode:'+code+' success~');
        })
        return res.send({joinCode: code});
    })
}

exports.editAct = function(req, res, next){
    var actId = req.params.id,
        me = req.params.currentUser;
    Activity.getActivityById(actId, function(err, act){
        var rendData = {
            act: act,
            startTime: dateUtil.getZhDate(act.startTime),
            time: dateUtil.formatDateNew(act.startTime, 'yyyy-MM-dd hh:mm'),
            faction: act.belongFaction,
            me: me
        }
        return res.render('activity/edit_faction_act', rendData);
    });
}

exports.invite = function(req, res, next){
    var actId = req.params.id,
        me = req.params.currentUser,
        hasJoined = false;
    var fromUserId = req.params.from;
    Activity.getActivityById(actId, function(err, act){
        if(err){logger.error(err.message);
            return res.render('others/error', {error: err});}
        //用缓存队列判断是否签到
        redisManager.isInAttends(actId, me.id, function(err, resp){
            if(resp == 1){
                hasJoined = true;
            }
            redisManager.getAttendActScore(actId, me.id, function(err, score){
                if(score){
                    me.score = score;
                }
                redisManager.getAttendActNo(actId, me.id, function(err, no){
                    if(no){
                        me.no = no;
                    }
                    // 检查过期
                    _checkActHasExpired(act, function(err, data){
                        User.getUserById(me.id, function(err, user){
                            _routeByType(res, act, data, me, hasJoined, fromUserId, user.card);
                        })
                    });
                })
            })
        });
    })
}

exports.fetchAttends = function(req, res){
    var actId = req.params.actId;
    Activity.getActivityById(actId, function(err, act){
        var attends = act.attends;
        if(attends.length > 0){
            var idArr = [];
            attends.forEach(function(attend){
                idArr.push(attend.id);
            })
            User.findByIdArray(idArr, function(err, attends){
                res.send({attends: attends})
            })
        }else{
            res.send({attends: []})
        }
    })
}
function _routeByType(res, act, data, user, hasJoined, fromUserId, card){
    var rendData = {
        act: data,
        startTime: dateUtil.getZhDate(act.startTime),
        day: dateUtil.getWeekday(act.startTime),
        me: user,
        hasJoined: hasJoined,
        score: user.score,
        no: user.no,
        from: fromUserId,
        card: card
    }
    var forward = 'activity/invite';
    if(act.actType === 'kecheng'){
        forward = 'activity/faction_invite';
    }
    return res.render(forward, rendData);
}
function _checkActHasExpired(act, callback){
    if(!act.hasExpired){
        console.log('判断过期')
        if(new Date().getTime() - act.startTime.getTime() > 7200000){ //2个小时 、2天:86400000
            Activity.setExpired(act._id, function(err, data){
                logger.debug('act :['+data._id+'] has been set Expired!');
                redisManager.delAttendSet(act._id, function(err, resp){
                    logger.debug('delete act:['+act._id+'] attend set cache!');
                })
                callback(err, data);
            })
        }else{
            callback(null, act);
        }
    }else{
        console.log('已经过期');
        callback(null, act);
    }
}

exports.apply = function(req, res, next){
    var actId = req.body.id,
        me = req.params.currentUser;
        me.remark = req.body.remark || '我来啦~';
        me.factionId = req.body.faction || null;
    var from = req.body.from;
    Activity.addAtend(actId, me, function(err, data){
        if(err){
            logger.error(err.message);
            return res.send({error: err.outside});
        }
        if(data){
            var score = {}
            if(data.outside){
                return res.send({data: 'outside'});
            }
            if(data.already){
                return res.send({data: 'already'});
            }
            if(data.score){
                score = data.score;
                User.increaseScore(me, data.score, function(err, data){});
                //TODO: 给from 加分;
                if(from){
                    FactionMember.addScore(me.factionId, from, score, function(err, fmresp){
                        if(fmresp){
                            console.log(fmresp.score);
                            _sentScoreTemplateMsg(from, score, me, me.factionId, function(err, resp){})
                        }
                    })
                }
            }
            redisManager.getAttendActNo(actId, me.id, function(err, no){
                return res.send({data: {
                    id: me.id,
                    name: me.name,
                    time: new Date(),
                    score: score,
                    No: no
                }});
            });
        }
    });
}
function _sentScoreTemplateMsg(from, score, currUser, faction, callback){
    redisManager.getUserById(from, function(err, user){
        if(err) return logger.error(err);
        FactionMember.getFmByUserAndFactionId(from, faction, function(err, fm){
            if(err) return logger.error(err);
            var url = config.wechat_url + 'user/',
                data = {
                    title: '好友['+currUser.name+']通过你分享的链接抢到了快乐镑，分你一半哟~以后继续分享哈~\(≧▽≦)/~',
                    userName: user.name,
                    time: dateUtil.formatDate(new Date()),
                    type: '签到抢快乐镑',
                    creditChange: '本次快乐镑',
                    score: score,
                    creditName: fm.faction.name + '快乐镑',
                    total: fm.score
                }
            Message.buildTemplateMsg(user.openid, url, data, function(msgJson){
                console.log(msgJson)
                Message.sendTemplateMsg(msgJson, function(err, resp){
                    if(err) return logger.error(err);
                    console.log('发送模版消息');
                    console.log(resp);
                    callback(err, resp)
                })
            })
        });
    });

}
exports.cancel = function(req, res, next){
    var actId = req.body.id,
        me = req.params.currentUser;
    Activity.cancelAttend(actId, me, function(err, data){
        if(err){
            logger.error(err.message);
            return res.send({error: err});
        }
        return res.send({data: data});
    });
}

exports.showActlist = function(req, res, next){
    var me = req.params.currentUser,
        pageNo = req.params.pageNo?req.params.pageNo: 1,
        pageSize = 5;
    //分页暂定 5个
    Activity.pageMyActlist(me.id, pageNo, pageSize, function(err, acts){
        if(err){
            logger.error(err.message);
            return res.render({error: err})
        }
        return res.render('activity/act_list', {acts: acts,
            pageNo: pageNo,
            pageSize: pageSize,
            user:me,
            dateUtil:dateUtil})
    })
}

exports.fetchActs = function(req, res, next){
    var me = req.params.currentUser,
        pageNo = parseInt(req.body.pageNo) + 1,
        pageSize = 5;
    Activity.pageMyActlist(me.id, pageNo, pageSize, function(err, acts){
        if(err){
            logger.error(err.message);
            return res.send({error: err})
        }
        return res.send({acts: acts,
            pageNo: pageNo,
            user:me})
    })
}

exports.actScoreList = function(req, res, next){
    var me = req.params.currentUser,
        actId = req.params.actId,
        no = req.params.no,
        myScore = req.params.score;
    User.getUserById(me.id, function(err, user){
        Activity.getActivityById(actId, function(err, act){
            var faction = act.belongFaction;
            res.render('activity/act_scorelist',
                {   user: me,
                    myCard: user.card,
                    actId: actId,
                    actName: act.name,
                    no: no,
                    factionName: faction.name,
                    myScore: myScore});
        });
    })
}

exports.pickUpGift = function(req, res, next){
    var me = req.params.currentUser,
        actId = req.body.actId,
        factionId = req.body.factionId;
    var max = 110, min = 20;
    var score = Math.floor(min+Math.random()*(max-min));
    FactionMember.addScore(factionId, me.id, score, function(err, resp){
         if(err) logger.error(err.message);
         console.log('User ['+me.id+'] in faction ['+factionId+'] add score:'+score);
        res.send({data: score});
    });
}
